package frame.system.web.auth;

import frame.base.*;
import frame.system.qo.AuthQo;
import frame.system.service.DeptService;
import frame.system.service.RoleService;
import frame.system.service.UserService;
import frame.system.to.User;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.Collection;
import java.util.List;

@Controller
@RequestMapping(UserWeb.DIR)
public class UserWeb extends BaseWeb{

    public static final String DIR = "/web/system/auth/user";

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private SessionDAO sessionDAO;

    @RequiresRoles(value = {"admin"})
    @RequestMapping("/index")
    public String index(Model model, AuthQo qo) {
        model.addAttribute("dir", DIR);
        model.addAttribute("qo", qo);
        model.addAttribute("roles", roleService.allList());
        model.addAttribute("depts", deptService.allList());

        return "system/auth/userlist";
    }
    @RequestMapping("/table")
    @ResponseBody
    public BootstrapTable<User> table(AuthQo qo) {
        return userService.pageList(qo);
    }
    @RequestMapping("/add")
    @ResponseBody
    public Ajax add(@Valid() User user, BindingResult bd, @RequestParam(name = "role",required = false) String[] roles) {
        //System.out.println(user);
        try {
            super.checkFormData(bd);
            List<Integer> roleIds = strId2Integer(roles);
            userService.add(user, roleIds);
            return Ajax.success(user,"数据创建成功！");
        } catch (Exception e) {
            return Ajax.faild("数据创建失败：" + e.getMessage());
        }
    }

    @RequestMapping("/delete")
    @ResponseBody //1_3_44
    public Ajax delete(String[] ids) {
        //System.out.println("delete ids.length = " + ids.length);
        try {
            List<Integer> idList = strId2Integer(ids);
            int re =  userService.remove(idList);
            return Ajax.success(re, "数据删除成功");
        } catch (Exception e) {
            return Ajax.faild("数据删除失败：" + e.getMessage());
        }
    }

    @PostMapping("/update")
    @ResponseBody
    public Ajax update(@Valid() User user, BindingResult bd, @RequestParam(name = "role",required = false) String[] roles) {
        //System.out.println("update id = " + user.getId());
        try {
            checkFormData(bd);
            List<Integer> roleIds = strId2Integer(roles);
            int re = userService.updateCommon(user, roleIds);
            return Ajax.success(re,"数据更新成功！");
        } catch (Exception e) {
            return Ajax.faild("数据更新失败：" + e.getMessage());
        }
    }

    @PostMapping("/resetpassword")
    @ResponseBody
    public Ajax resetpassword(@RequestParam("id") Integer id) {
        //System.out.println("resetpassword id = " + id);
        try {
            User user = userService.selectByPrimaryKey(id);
            user.setPassword(User.PASSWORD);
            int re = userService.updatePassword(user);
            return Ajax.success(re,"密码已重置为【"+User.PASSWORD+"】！");
        } catch (Exception e) {
            return Ajax.faild("密码重置失败：" + e.getMessage());
        }
    }

    @RequestMapping("/get")
    @ResponseBody
    public Ajax get(String id) {
        //System.out.println("get id = " + id);
        try {
            Integer id0 = strId2Integer(id);
            User user = userService.selectByPrimaryKey(id0);
            return Ajax.success(user,"数据查询成功");
        } catch (Exception e) {
            return Ajax.faild("数据查询失败：" + e.getMessage());
        }
    }
    @RequestMapping("/typeahead")
    @ResponseBody
    public List<Typeahead<Integer>> typeahead(AuthQo qo) {
        return userService.typeahead(qo);
    }

    @PostMapping("/countByUsername")
    @ResponseBody
    public Ajax countByUsername(AuthQo qo) {
        try {
            int re = userService.countByUsername(qo);
            return Ajax.success(re, "用户名数量查询成功！");
        } catch (Exception e) {
            return Ajax.faild("失败：" + e.getMessage());
        }
    }

    /**
     * 强制下线
     * @param id
     * @return
     */
    @RequestMapping("/offline")
    @ResponseBody
    public Ajax offline(@RequestParam("id") Integer id) {
        try {
            Collection<Session> sessions = sessionDAO.getActiveSessions();
            sessions.forEach(session -> {
                System.out.println(session.getId() +  " " +session.getTimeout());
                User user = (User)session.getAttribute(BaseConstant.SYSTEM_LOGIN);
                if (user != null && id.equals(user.getId())) {
                    session.setTimeout(0);
                    System.out.println("session id = " + id + " offline");
                }
            });
            return Ajax.success(sessions, "操作成功！");
        } catch (Exception e) {
            return Ajax.faild("操作失败：" + e.getMessage());
        }
    }
}
